<template>
  <view class="flex flex-col bg-white">
    <!-- 顶部导航栏 -->
    <view
      class="relative z-10 h-90rpx flex flex-shrink-0 items-center justify-between border-b-1 border-b-[#eee] bg-white pt-60rpx"
    >
      <view class="ml-20rpx h-60rpx w-60rpx flex items-center justify-center" @tap="onBack">
        <image src="https://ceshiweb.picaime.com/static/images/order/back.png" class="h-36rpx w-36rpx" mode="aspectFit" />
      </view>
      <view class="pointer-events-none absolute left-0 right-0 flex items-center justify-center">
        <text class="text-36rpx text-black font-bold leading-[49.4rpx] tracking-0">
          赊欠录入
        </text>
      </view>
    </view>

    <view class="bg-[rgba(242,247,255,1)]">
      <view class="mb-20rpx mt-20rpx border-b-1rpx border-b-[#eee] bg-white p-20rpx">
        <text class="mb-20rpx block text-17px text-black font-bold">
          买家名称
        </text>
        <view class="flex items-center rounded-5px bg-[rgba(242,247,255,1)] pl-12px">
          <input v-model="buyerName" class="h-60rpx flex-1 text-32rpx" placeholder="请导入买家">
          <button
            class="h-80rpx w-120rpx border-1px border-[rgba(229,229,229,1)] rounded-br-7.43px rounded-tr-7.43px bg-[rgba(67,207,124,1)] text-center text-32rpx text-white font-bold leading-80rpx"
            @click="importBuyerName"
          >
            导入
          </button>
        </view>
      </view>

      <view class="mb-20rpx mt-20rpx border-b-1rpx border-b-[#eee] bg-white p-20rpx">
        <text class="mb-20rpx block text-17px text-black font-bold">
          赊欠时间
        </text>
        <view class="flex items-center rounded-5px bg-[rgba(242,247,255,1)] pl-12px">
          <input
            v-model="outOfStockDate" class="h-60rpx flex-1 text-32rpx" readonly placeholder="请选择赊欠时间"
            @click="showDatePicker"
          >
          <button
            class="h-80rpx w-120rpx flex items-center justify-center border-1px border-[rgba(229,229,229,1)] rounded-br-7.43px rounded-tr-7.43px bg-[rgba(67,207,124,1)]"
            @click="showDatePicker"
          >
            <view class="flex items-center justify-center">
              <u-icon name="calendar" color="#ffffff" size="28" />
            </view>
          </button>
        </view>
      </view>

      <view class="mb-20rpx mt-20rpx border-b-1rpx border-b-[#eee] bg-white p-20rpx">
        <text class="mb-20rpx block text-17px text-black font-bold">
          赊欠金额
        </text>
        <view class="flex items-center rounded-5px bg-[rgba(242,247,255,1)] pl-12px">
          <input v-model="outOfStockAmount" class="h-60rpx flex-1 text-32rpx" placeholder="请输入赊欠金额">
          <div
            class="h-80rpx w-120rpx border-1px border-[rgba(229,229,229,1)] rounded-br-7.43px rounded-tr-7.43px bg-[rgba(67,207,124,1)] text-center text-32rpx text-white font-bold leading-80rpx"
          >
            元
          </div>
        </view>
      </view>

      <view class="mb-20rpx mt-20rpx border-b-1rpx border-b-[#eee] bg-white p-20rpx">
        <text class="mb-20rpx block text-17px text-black font-bold">
          备注
        </text>
        <view class="rounded-5px bg-[rgba(242,247,255,1)] pl-12px">
          <textarea v-model="remarks" class="w-full p-10rpx text-32rpx" placeholder="请输入备注" auto-height />
        </view>
      </view>

      <view class="mt-40rpx p-20rpx">
        <text class="mb-20rpx block text-28rpx text-[#666]">
          上传赊欠凭证 ({{ uploadedFiles.length }}/1)
        </text>
        <view class="flex flex-wrap gap-20rpx">
          <view
            v-for="(item, index) in uploadedFiles" :key="index"
            class="relative h-200rpx w-200rpx border-1rpx border-[#ddd] rounded-8rpx border-dashed"
          >
            <image class="h-full w-full rounded-8rpx" :src="item" mode="aspectFill" />
            <view
              class="absolute h-40rpx w-40rpx rounded-full bg-red text-center text-white leading-40rpx -right-10rpx -top-10rpx"
              @click="uploadedFiles.splice(index, 1)"
            >
              ×
            </view>
          </view>
          <view
            v-if="uploadedFiles.length < 1"
            class="h-200rpx w-200rpx flex flex-col items-center justify-center border-1rpx border-[#007aff] rounded-8rpx border-dashed text-[#007aff]"
            @click="handleUpload"
          >
            <text class="mb-10rpx text-48rpx">
              +
            </text>
            <text>拍照上传</text>
          </view>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="mt-40rpx flex justify-center p-20rpx">
        <view class="h-90rpx w-100% flex items-center justify-center rounded-10rpx bg-[#43CF7C]" @tap="handleSubmit">
          <text class="text-34rpx text-white font-bold">
            提交
          </text>
        </view>
      </view>
    </view>

    <!-- 日期选择器 -->
    <up-datetime-picker
      ref="datetimePickerRef" v-model="dateTimeValue" :show="showTimePicker" mode="datetime"
      @confirm="timeConfirm" @cancel="timeCancel"
    />
  </view>
</template>

<script lang="ts" setup>
import type { LuruDataParams } from '@/api/statistics/types';
import { onMounted, ref } from 'vue';
import { addLuruData } from '@/api/statistics';

// 日期时间选择器相关变量
const showTimePicker = ref(false);
const dateTimeValue = ref(Date.now());
const datetimePickerRef = ref(null);

// 响应式状态
const buyerName = ref<string>('');
const maijiaId = ref<number>(0);
const outOfStockDate = ref<string>(formatTime(new Date()));
const outOfStockAmount = ref<string>('');
const remarks = ref<string>('');
const uploadedFiles = ref<string[]>([]);
const isSubmitting = ref(false);

// 格式化时间为YYYY-MM-DD HH:mm格式
function formatTime(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 方法
const onBack = () => {
  uni.navigateBack();
};

const handleSubmit = async () => {
  if (!buyerName.value) return uni.showToast({ title: '请填写买家名称', icon: 'none' });
  if (!outOfStockAmount.value) return uni.showToast({ title: '请填写赊欠金额', icon: 'none' });
  if (!uploadedFiles.value.length) return uni.showToast({ title: '请上传赊欠凭证', icon: 'none' });

  if (isSubmitting.value) return;
  isSubmitting.value = true;

  uni.showLoading({ title: '提交中...' });

  try {
    // 构建API参数
    const params: LuruDataParams = {
      imageUrl: uploadedFiles.value[0], // 使用第一张图片作为凭证
      maijia: buyerName.value,
      maijia_id: maijiaId.value,
      money: outOfStockAmount.value,
      time: outOfStockDate.value,
    };

    // 调用API提交数据
    const res = await addLuruData(params);

    if (res.code === 200) {
      uni.showToast({ title: '提交成功', icon: 'success' });
      // 提交成功后返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
    else {
      uni.showToast({ title: res.msg || '提交失败', icon: 'none' });
    }
  }
  catch (error) {
    console.error('提交数据失败:', error);
    uni.showToast({ title: '提交失败，请重试', icon: 'none' });
  }
  finally {
    uni.hideLoading();
    isSubmitting.value = false;
  }
};

const importBuyerName = () => {
  uni.navigateTo({ url: '/pages/common/selectBuyer/index' });
};

// 监听选择买家页面返回的数据
onMounted(() => {
  uni.$on('updateSelectedBuyer', (data: { id: number; maijia_id: string; name: string }) => {
    if (data && data.name) {
      buyerName.value = data.name;
      maijiaId.value = Number.parseInt(data.maijia_id);
    }
  });
});

// 打开日期选择器
const showDatePicker = () => {
  showTimePicker.value = true;
};

// 确认日期选择
const timeConfirm = () => {
  try {
    // 将时间戳格式化为YYYY-MM-DD HH:mm格式
    const date = new Date(dateTimeValue.value);
    if (isNaN(date.getTime())) {
      throw new TypeError('无效的日期');
    }

    // 更新显示的时间
    outOfStockDate.value = formatTime(date);

    uni.showToast({
      title: '时间设置成功',
      icon: 'success',
    });
    showTimePicker.value = false;
  }
  catch (error) {
    console.error('日期格式化错误:', error);
    uni.showToast({
      title: '日期格式错误',
      icon: 'none',
    });
  }
};

// 取消日期选择
const timeCancel = () => {
  showTimePicker.value = false;
};

// 处理图片上传
const handleUpload = () => {
  uni.chooseImage({
    count: 1 - uploadedFiles.value.length,
    success: async (res) => {
      const tempFilePaths = Array.isArray(res.tempFilePaths) ? res.tempFilePaths : [res.tempFilePaths];

      // 开始上传
      for (const filePath of tempFilePaths) {
        uni.showLoading({ title: '上传中...' });

        try {
          const uploadResult = await uploadFile(filePath);
          if (uploadResult && uploadResult.code === 200) {
            // 上传成功，添加到图片列表
            uploadedFiles.value = [...uploadedFiles.value, uploadResult.data.path];
          }
          else {
            uni.showToast({ title: uploadResult?.msg || '上传失败', icon: 'none' });
          }
        }
        catch (error) {
          console.error('上传失败:', error);
          uni.showToast({ title: '上传失败，请重试', icon: 'none' });
        }
        finally {
          uni.hideLoading();
        }
      }
    },
  });
};

// 上传文件到服务器的方法
const uploadFile = (filePath: string): Promise<any> => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: 'https://ceshiweb.picaime.com/syapi/upload/upload',
      filePath,
      name: 'file',
      success: (uploadRes) => {
        try {
          // 解析JSON字符串
          const data = JSON.parse(uploadRes.data);
          resolve(data);
        }
        catch (e) {
          reject(e);
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};
</script>
